package net.zjitc.controller;

import net.zjitc.domain.AdminUser;
import net.zjitc.domain.User;
import net.zjitc.service.AdminService;
import net.zjitc.service.UserService;
import net.zjitc.service.impl.AdminServiceImpl;
import net.zjitc.service.impl.UserServiceImpl;
import net.zjitc.utils.URLMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * 2 * @Author: 洪瑶
 * 3 * @Date: 2018/11/22 10:20
 * 4
 */
public class loginController {

    @URLMapping(url = "/loginUI")
    public String loginUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        return "/WEB-INF/user/login.jsp";
    }

    @URLMapping(url = "/user_loginPage")
    public String user_registPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return "/WEB-INF/user/login.jsp";
    }

    @URLMapping(url = "/user_login")
    public String user_login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String loginName = request.getParameter("username");
        String loginPsw = request.getParameter("password");
        String loginCheck = request.getParameter("validatecode");
        String lc = (String) request.getSession().getAttribute("loginCheck");       //getAttribute()
        UserService service = new UserServiceImpl();
        try {
            User user = service.login(loginName,loginPsw);
            HttpSession session = request.getSession();
            PrintWriter writer = response.getWriter();
            if (user != null && loginCheck.equals(lc) && user.getState()==1)
            {
                session.setAttribute("user",user);
                return "/index.jsp";
            } else if (!loginCheck.equals(lc)){
                request.setAttribute("msg","验证码错误");
            } else if (user.getState() != 1){
                request.setAttribute("msg","用户未激活，点击<a href=\"#\">激活</a>");
            }else {
                request.setAttribute("msg","用户名或密码错误");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "/WEB-INF/user/login.jsp";
    }



    @URLMapping(url = "/user_exit")
    public String user_exit(HttpServletRequest request,HttpServletResponse response){
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        return "/index.jsp";
    }
}
